package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.GlideUtil;
import com.shwread.android.qysw10000227.R;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.CommentView;
import com.shwread.android.ui.widget.ListenSoftInputMethodLinearLayout;
import com.shwread.android.ui.widget.ListenSoftInputMethodLinearLayout.OnSoftInputMethodListener;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.android.ui.widget.xlistview.XListView;
import com.shwread.android.ui.widget.xlistview.XListView.IXListViewListener;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.face.QryCommentListAction;

import java.util.ArrayList;
import java.util.List;

import logic.bean.BookInfo;
import logic.bean.CommentBean;
import logic.bean.ImageCollection;
import logic.bean.RegionContentItemBean;
import logic.bean.SingleBook;
import logic.bean.SingleNews;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.DateUtil;
import logic.util.NetworkUtil;
import logic.util.ScreenUtil;
import logic.util.Util;


/**
 * @Project： Shwread
 * @Title：InteractionCenterCommentListActivity
 * @Description：评论列表
 * @Author：zhangnannan
 * @Date：2015年3月4日
 */
public class InteractionCenterCommentListActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener,
        IXListViewListener
{
	private BaseBusinessActivity              bActivity;
	private Context                           context;
	private TextView                          tvTitle;
	private Button                            butBack;
	private XListView                         xListView;
	private CommentView                       commentView;
	
	private CommentListAdapter                commentListAdapter;
	
	private List<CommentBean>                 resultInfo;                //临时存放从服务器取回的数据
	private List<CommentBean>                 commentList;               //显示数据用的List
	                                                                      
	private String                            targetType;                //评论的内容类型       
	private String                            targetValue;               //评论的内容值
	private long                              currentCommentTime = 0L;   //最后一条记录的评论时间戳,首次为零
	private int                               pageNumber         = 20;   //每页显示记录数
	private long                              refrushTime;               // 刷新时间
	                                                                      
	private ListenSoftInputMethodLinearLayout root_view;
	private boolean                           inputMethodIsShow  = false;
	
	private LoadingView                       loadingView;
	private ImageView                    ivCover;
	private TextView                          tvCommentTitle, tvCommentIntro;
	private RegionContentItemBean             interactionCommentBean;
	private String                            commentType;                   //基础类型 1=单条资讯 2=多条资讯 3=音频 4=视频 5=图集 6=单本书籍 7多本书籍
	private View                              topView;
	private boolean                           isCommented = false;
	@SuppressLint ("HandlerLeak")
	private Handler handler = new Handler()
	                        {
		                        @Override
		                        public void handleMessage(Message msg) {
			                        switch (msg.what) {
										case DefaultConsts.COMMENT_LIST_UPDATEUI:
											setData(msg);
											break;
										case DefaultConsts.COMMENT_SUBMIT_SUCCESS:
											isCommented = true;
											getData(-1);
											//											Util.showToast(context, "评论成功");
											break;
										case DefaultConsts.COMMENT_SUBMIT_ERROR:
											//											Util.showToast(context, "评论失败");
											break;
									}
								}
	                        };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.interaction_comment_list_lay);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		bActivity = this;
		context = this;
		resultInfo = new ArrayList<CommentBean>();
		commentList = new ArrayList<CommentBean>();
		commentListAdapter = new CommentListAdapter();
		Bundle bundle = getIntent().getExtras();
		if (bundle != null)
		{
			interactionCommentBean = (RegionContentItemBean) bundle.getSerializable(DefaultConsts.COMMENT_TARGET_VALUE);
			if (interactionCommentBean != null)
			{
				commentType = interactionCommentBean.getType();
			}
		}
		else
		{
			finish();
			return;
		}

		findView();
		initLoadingView();
		addListener();

		getData(0);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		if (null != commentView) commentView.hideInputMethod();
	}
	
	private void initLoadingView() {
		loadingView = (LoadingView) findViewById(R.id.interaction_comment_list_lay_loading_view);
		loadingView.setDefaultConfig();
		loadingView.setEmptyClickListener(new ViewClick());
		loadingView.setFailClickListener(new ViewClick());
		loadingView.changeLoadingStatus(0);
		loadingView.setVisibility(View.VISIBLE);
		xListView.setVisibility(View.GONE);
	}
	
	@Override
	public Handler getUIHandler() {
		return handler;
	}
	
	private void findView() {
		root_view = (ListenSoftInputMethodLinearLayout) findViewById(R.id.interaction_comment_list_view);
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		butBack = (Button) findViewById(R.id.common_header_back);
		tvTitle.setText(getResources().getString(R.string.comment_title_text));
		tvTitle.setVisibility(View.GONE);
		butBack.setVisibility(View.VISIBLE);

		topView = LayoutInflater.from(context).inflate(R.layout.interaction_comment_lay_top_view, null);
		ivCover = (ImageView) topView.findViewById(R.id.interaction_comment_list_lay_cover_iv);
		tvCommentTitle = (TextView) topView.findViewById(R.id.interaction_comment_list_lay_title_tv);
		tvCommentIntro = (TextView) topView.findViewById(R.id.interaction_comment_list_lay_author_tv);

		if (commentType.equals("6") || commentType.equals("7"))
		{
			//设置书籍信息的图片大小
			ViewGroup.LayoutParams layoutparams = ivCover.getLayoutParams();
			int width = ScreenUtil.dip2px(44);
			int height = ScreenUtil.dip2px(59);
			layoutparams.width = width;
			layoutparams.height = height;
			ivCover.setLayoutParams(layoutparams);
		}
		else
		{
			//设置非书籍信息的图片大小
			ViewGroup.LayoutParams layoutparams = ivCover.getLayoutParams();
			int width = ScreenUtil.dip2px(57);
			layoutparams.width = width;
			layoutparams.height = width;
			ivCover.setLayoutParams(layoutparams);
		}

		if (commentType.equalsIgnoreCase("1"))
		{ //单条资讯          1=单条资讯 2=多条资讯 3=音频 4=视频 5=图集 6=单本书籍 7多本书籍

			// targetType//评论类型  1为书籍，  2 为资讯类的评论， 3为 图片， 4为图集
			SingleNews singleNews = interactionCommentBean.getSingleNews();
			targetType = "2";
			targetValue = Long.toString(singleNews.getModelContentDetailId());

			tvCommentTitle.setText(singleNews.getTitle());
			tvCommentIntro.setText(singleNews.getShortDesc());

			if (!Util.isEmpty(singleNews.getCoverImageUrl()))
			{
//				ivCover.setImageUrl(singleNews.getCoverImageUrl());

				GlideUtil.load(context, singleNews.getCoverImageUrl(), R.drawable.atlas_default_img, ivCover);
			}
			else
			{
				ivCover.setImageResource(R.drawable.atlas_default_img);
			}

		}
		//		else if (contentType.equalsIgnoreCase("3"))
		//		{ //音频
		//
		//		}
		//		else if (contentType.equalsIgnoreCase("4"))
		//		{ //视频
		//
		//		}
		else if (commentType.equalsIgnoreCase("5"))
		{ //图集     1=单条资讯 2=多条资讯 3=音频 4=视频 5=图集 6=单本书籍 7多本书籍

			// targetType  //评论类型  1为书籍，  2 为资讯类的评论， 3为 图片， 4为图集
			ImageCollection imageSet = interactionCommentBean.getImageSet();
			targetType = "4";
			targetValue = Long.toString(imageSet.getImageCollectionId());

			tvCommentTitle.setText(imageSet.getTitle());
			tvCommentIntro.setText(imageSet.getShortDesc());

			if (!Util.isEmpty(imageSet.getCoverImageUrl()))
			{
//				ivCover.setImageUrl(imageSet.getCoverImageUrl());
				GlideUtil.load(context, imageSet.getCoverImageUrl(), R.drawable.atlas_default_img, ivCover);
			}
			else
			{
				ivCover.setImageResource(R.drawable.atlas_default_img);
			}
		}
		else if (commentType.equalsIgnoreCase("6"))
		{ //单本书籍

			// targetType//评论类型  1为书籍，  2 为资讯类的评论， 3为 图片， 4为图集
			SingleBook singleBook = interactionCommentBean.getSingleBook();
			targetType = "1";
			targetValue = Long.toString(singleBook.getBookId());

			//显示标题和作者
			tvCommentTitle.setText(singleBook.getBookInfo().getName());
			tvCommentIntro.setText(singleBook.getBookInfo().getAuthor());

			if (!Util.isEmpty(singleBook.getBookInfo().getLogoUrl()))
			{
//				ivCover.setImageUrl(singleBook.getBookInfo().getLogoUrl());
				GlideUtil.load(context, singleBook.getBookInfo().getLogoUrl(), R.drawable.bookcover_default, ivCover);
			}
			else
			{
				ivCover.setImageResource(R.drawable.bookcover_default);
			}

		}

		xListView = (XListView) findViewById(R.id.interaction_comment_list_lay_list);
		xListView.addHeaderView(topView);
		commentView = (CommentView) findViewById(R.id.interaction_comment_list_lay_comment_view);

		root_view.setOnSoftInputMethodListener(new OnSoftInputMethodListener()
		{
			@Override
			public void OnSoftInputMethodChanged(boolean isShow) {
				inputMethodIsShow = isShow;
			}
		});
	}
	
	private boolean resetCommentView() {
		if (inputMethodIsShow)
		{
			commentView.setDefaultHint();
			commentView.setCommentParams(this, targetType, targetValue);
			commentView.hideInputMethod();
			return true;
		}
		return false;
	}
	
	private void addListener() {
		butBack.setOnClickListener(this);
		xListView.setPullLoadEnable(true);
		xListView.hideLoadMore();
		xListView.setXListViewListener(this);
		xListView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (inputMethodIsShow)
				{
					commentView.setDefaultHint();
					commentView.setCommentParams(bActivity, targetType, targetValue);
					commentView.hideInputMethod();
					return;
				}
				if (position < 2) return;
				position -= 2;
				CommentBean info = (CommentBean) commentList.get(position);
				if (Const.phone_number.equals(info.getCommentUserAccount()))
				{
					commentView.setDefaultHint();
					commentView.setCommentParams(bActivity, targetType, targetValue);
				}
				else
				{
					commentView.setHintString(info.commentUserNickName);
					commentView.setReplyParams(bActivity, targetType, targetValue, info.commentUserId, info.commentUserAccount, info.commentId);
				}
				commentView.showInputMethod();
			}
		});

		topView.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v) {
				if (commentType.equalsIgnoreCase("1"))
				{ //单条资讯
				  //todo 跳转到图文详情
					SingleNews singleNews = interactionCommentBean.getSingleNews();
					gotoImageTextActivity(singleNews.getHtmlUrl(), singleNews.getTitle(), singleNews.getModelContentDetailId() + "");
				}
				else if (commentType.equalsIgnoreCase("2"))
				{//多条资讯
				 //每个已经处理了， 这里不需要处理
				}
				else if (commentType.equalsIgnoreCase("3"))
				{//音频

				}
				else if (commentType.equalsIgnoreCase("4"))
				{//视频

				}
				else if (commentType.equalsIgnoreCase("5"))
				{ //图集
				  //todo 跳转到查看图集图片
					gotoImageViewerActivity(/* ,2 */);
				}
				else if (commentType.equalsIgnoreCase("6"))
				{ //单本书籍
				  //跳转到书籍详情
					SingleBook singleBook = interactionCommentBean.getSingleBook();
					BookInfo bookInfo = singleBook.getBookInfo();
					if (bookInfo == null) return;
					//#ifdef SHOW_OLDBOOKDETAIL
					//$ Intent intent = new Intent(mContext, BookDetailActivity.class);
					//#else
					Intent intent = new Intent(context, NewBookDetailActivity.class);
					//#endif
					bookInfo.setAuthor("");
					intent.putExtra("BookInfo", bookInfo);
					context.startActivity(intent);
				}
			}
		});
		commentView.setCommentParams(bActivity, targetType, targetValue);
	}
	
	/**
	 * 跳转到图文详情页
	 *
	 * @param url
	 */
	private void gotoImageTextActivity(String url, String title, String contentDetailId) {
		Intent intent = new Intent(context, ImageTextActivity.class);
		intent.putExtra(DefaultConsts.req_url_s, url);
		intent.putExtra(DefaultConsts.title_s, title);
		intent.putExtra(DefaultConsts.COMMENT_TARGET_TYPE, "2");
		intent.putExtra(DefaultConsts.COMMENT_TARGET_VALUE, contentDetailId);
		context.startActivity(intent);
	}
	
	/**
	 * 跳转到查看图集的页面
	 *
	 * @param position
	 * @param type
	 *            1 为直接进入查看, 2 为可能要进入到瀑布流页面
	 */
	private void gotoImageViewerActivity(/* , int type */) {
		int imgCounts = 0;

		ImageCollection imageSet = interactionCommentBean.getImageSet();
		imgCounts = imageSet.getImageCollectionNum();
		Intent intent;
		if (imgCounts == 0)
		{
			Toast.makeText(context, "图集已下架", Toast.LENGTH_SHORT).show();
			return;
		}
		if (/* type == 1 || ( type == 2 && */imgCounts <= 5/* ) */)
		{
			//直接进入看图片
			intent = new Intent(context, AtlasSeeActivity.class);
			intent.putExtra(AtlasSeeActivity.FROM_TYPE, DefaultConsts.TAG_FROM_ENTERPRISE);
			intent.putExtra(AtlasSeeActivity.IMAGE_COUNT, imgCounts);
		}
		else
		{//进入到瀑布流页面
			intent = new Intent(context, AtlasActivity.class);
			intent.putExtra(AtlasActivity.ATLAS_NAME, imageSet.getTitle());
		}
		//todo  设置图集的数据
		intent.putExtra(AtlasActivity.ATLAS_ID, imageSet.getImageCollectionId());
		context.startActivity(intent);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				commentView.hideInputMethod();
				setReturnResult( );
				finish();
				break;
		}
	}
	
	@Override
	public void onBackPressed() {
		setReturnResult( );
		super.onBackPressed();
	}
	
	private void setReturnResult( ){
			setResult(this.RESULT_OK);
	}
	
	public void setData(Message msg) {
		if (msg == null) return;
		final int flag = Integer.valueOf(msg.obj.toString());
		if (2 == flag && (resultInfo == null || resultInfo.isEmpty() || resultInfo.size() < pageNumber))
		{
			//TODO
			xListView.setReadyHint("没有更多数据了");
		}
		if (null != resultInfo && !resultInfo.isEmpty())
		{
			if (commentList != null && flag != 2) commentList.clear();

			commentList.addAll(resultInfo);
			resultInfo.clear();
		}

		if (null == commentList || commentList.isEmpty() || commentList.size() == 0)
		{
			loadingView.changeLoadingStatus(1);
			commentView.showInputMethod();
		}
		else
		{
			if (0 == flag || -1 == flag)
			{
				xListView.setAdapter(commentListAdapter);
				loadingView.setVisibility(View.GONE);
				//				contentView.setVisibility(View.VISIBLE);
				xListView.setVisibility(View.VISIBLE);
			}
			commentListAdapter.notifyDataSetChanged();
		}
		xListView.stopRefresh();
		xListView.stopLoadMore();
		xListView.hideLoadMore();

	}
	
	private String getNickName(CommentBean bean) {
		if (null == bean) return "";
		if (Util.isNotEmpty(bean.commentUserNickName)) return bean.commentUserNickName;
		final String account = bean.commentUserAccount;
		if (Util.isEmpty(account)) return "";
		return Util.formatPhone(account);
	}
	
	private String getContent(CommentBean bean) {
		if (null != bean) { return Util.isEmpty(bean.replyCommentUserNickName) ? bean.content : String.format("回复%s: %s", bean.replyCommentUserNickName, bean.content); }
		return "";
	}
	
	@Override
	public void onRefresh() {
		xListView.setReadyHint("");
		xListView.setPullLoadEnable(true);
		getData(1);
	}
	
	@Override
	public void onLoadMore() {
		getData(2);
	}
	
	/**
	 * @param flag
	 *            0 为首次加载、1为下拉刷新 2为上拉加载更多 -1为评论成功后刷新
	 */
	public void getData(int flag) {
		if (NetworkUtil.isNetAvailable(context))
		{
			if (flag == 2)
			{
				currentCommentTime = commentList.get(commentList.size() - 1).getCreateTime();
			}
			else
			{
				currentCommentTime = 0L;
				refrushTime = System.currentTimeMillis();
				xListView.setRefreshTime(DateUtil.getRegionTime(refrushTime));
			}
			new QryCommentListAction(context, targetType, targetValue, flag == -1 ? 0L : currentCommentTime, flag == -1 ? commentList.size() + 1 : pageNumber, new getCommentListActionListener(flag)).start();
		}
		else
		{
			if (flag == 0)
			{
				new NoNetDialog(context).show();
			}
			else
			{
				Util.showToast(bActivity, "请检查网络");
				xListView.stopRefresh();
				xListView.stopLoadMore();
			}
		}
	}
	
	private class ViewClick
	        implements
	        OnClickListener
	{
		@Override
		public void onClick(View v) {
			loadingView.changeLoadingStatus(0);
			loadingView.setVisibility(View.VISIBLE);
			xListView.setVisibility(View.GONE);
			getData(0);
		}
	}
	
	private class getCommentListActionListener
	        implements
	        ActionListener
	{
		private int flag; //0 为首次加载、1为下拉刷新    2为上拉加载更多

		private getCommentListActionListener(int flag) {
			this.flag = flag;
		}

		@SuppressWarnings ("unchecked")
		@Override
		public void OK(Object obj) {
			resultInfo = (List<CommentBean>) obj;

			Message msg = new Message();
			msg.what = DefaultConsts.COMMENT_LIST_UPDATEUI;
			msg.obj = flag;
			handler.sendMessage(msg);
		}

		@Override
		public void ERROR(int resultCode, final String message) {
			handler.post(new Runnable()
			{
				@Override
				public void run() {
					Util.showToast(context, message);
					if (0L == currentCommentTime) loadingView.changeLoadingStatus(-1);
				}
			});
		}

		@Override
		public void HTTPERROR(int statusCode) {
			handler.post(new Runnable()
			{
				@Override
				public void run() {
					if (0L == currentCommentTime) loadingView.changeLoadingStatus(-1);
				}
			});
		}
	}
	
	private class CommentListAdapter
	        extends
	        BaseAdapter
	{
		@Override
		public int getCount() {
			return (commentList == null ? 0 : commentList.size());
		}

		@Override
		public Object getItem(int position) {
			return (commentList == null ? null : commentList.get(position));
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			CommentListHolder commentListHolder = new CommentListHolder();
			if (convertView == null)
			{
				convertView = LayoutInflater.from(context).inflate(R.layout.interaction_comment_list_lay_list_item, null);
				commentListHolder.ivHeadImg = (ImageView) convertView.findViewById(R.id.interaction_comment_list_lay_list_item_head_img);
				commentListHolder.tvName = (TextView) convertView.findViewById(R.id.interaction_comment_list_lay_list_item_name_tv);
				commentListHolder.tvTime = (TextView) convertView.findViewById(R.id.interaction_comment_list_lay_list_item_time_tv);
				commentListHolder.tvContext = (TextView) convertView.findViewById(R.id.interaction_comment_list_lay_list_item_context_tv);
				convertView.setTag(commentListHolder);
			}
			else
			{
				commentListHolder = (CommentListHolder) convertView.getTag();
			}

			CommentBean commentBean = (CommentBean) getItem(position);
			commentListHolder.tvName.setText(getNickName(commentBean));
			commentListHolder.tvTime.setText(DateUtil.getRegionTime(commentBean.createTime));
			commentListHolder.tvContext.setText(getContent(commentBean));

			GlideUtil.roundnessload(context,commentBean.commentUserHeadImage,R.drawable.comment_list_default_head_img,commentListHolder.ivHeadImg);
			return convertView;
		}
	}
	
	private class CommentListHolder
	{
		TextView        tvName, tvContext, tvTime;
		ImageView ivHeadImg;
	}
}
